package com.liuxinlong.modules.material.service.impl;

import com.alibaba.fastjson.JSON;
import com.liuxinlong.api.ConvolutionInterface;
import com.liuxinlong.api.WeChatMessageInterface;
import com.liuxinlong.common.AosException;
import com.liuxinlong.common.ExcelImportCallBack;
import com.liuxinlong.common.ExcelImportService;
import com.liuxinlong.common.ImportResp;
import com.liuxinlong.common.RowError;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.RegionConstants;
import com.liuxinlong.constant.SystemConstants;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.ConvolutionStatusTypeEnum;
import com.liuxinlong.enums.MessageContentTypeEnum;
import com.liuxinlong.enums.MessagePushBusinessEnum;
import com.liuxinlong.enums.NotificationSourceEnum;
import com.liuxinlong.enums.RegionEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.MaterialConvolutionDao;
import com.liuxinlong.modules.dao.MaterialConvolutionLogDao;
import com.liuxinlong.modules.dao.MaterialRollupDao;
import com.liuxinlong.modules.dao.MaterialRollupResultDao;
import com.liuxinlong.modules.dao.NotificationDao;
import com.liuxinlong.modules.dao.ParameterDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.dao.UserRoleRelationDao;
import com.liuxinlong.modules.entity.MaterialConvolution;
import com.liuxinlong.modules.entity.MaterialConvolutionLog;
import com.liuxinlong.modules.entity.MaterialRollup;
import com.liuxinlong.modules.entity.MaterialRollupResult;
import com.liuxinlong.modules.entity.MessageConfiguration;
import com.liuxinlong.modules.entity.Notification;
import com.liuxinlong.modules.entity.SystemParameter;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.entity.UserRoleRelation;
import com.liuxinlong.modules.material.dto.MaterialConvolutionImportDto;
import com.liuxinlong.modules.material.service.MaterialConvolutionService;
import com.liuxinlong.modules.sync.service.SyncService;
import com.liuxinlong.push.MessagePushService;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物料成本卷积服务层实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2023年5月15日
 */
@Service
@Slf4j
public class MaterialConvolutionServiceImpl implements MaterialConvolutionService {

    @Autowired
    private MaterialConvolutionDao materialConvolutionDao;

    @Autowired
    private ExcelImportService excelImportService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ConvolutionInterface convolutionInterface;

    @Autowired
    private SyncService syncService;

    @Autowired
    private MaterialRollupDao materialRollupDao;

    @Autowired
    private ParameterDao parameterDao;

    @Autowired
    private NotificationDao notificationDao;

    @Autowired
    private WeChatMessageInterface weChatMessageInterface;

    @Autowired
    private MessagePushService messagePushService;

    @Autowired
    private MaterialConvolutionLogDao materialConvolutionLogDao;

    @Autowired
    private MaterialRollupResultDao materialRollupResultDao;

    @Autowired
    private UserRoleRelationDao userRoleRelationDao;

    @Override
    public List<Map<String, Object>> pageMaterialConvolutionList(Map<String, Object> queryParam) {
        List<MaterialConvolution> originList = materialConvolutionDao.pageConvolutionList(queryParam);
        int startNum = (Integer) queryParam.get("startNum");
        return completeResult(originList, startNum);
    }

    @Override
    public int getConvolutionRecordCount(Map<String, Object> queryParam) {
        return materialConvolutionDao.getConvolutionCount(queryParam);
    }

    @Override
//    @Transactional
    public void addMaterialConvolution(MaterialConvolution materialConvolution) {
        String materialNo = materialConvolution.getMaterialNo();
        String region = StringUtils.equals(materialConvolution.getRegion(), RegionEnum.WSCNJ.getName()) ?
                RegionEnum.WPCNJ.getName() : materialConvolution.getRegion();
        Map<String, Object> materialInfo = syncService.getOneMaterial(materialNo, region);
        if (ObjectUtils.isEmpty(materialInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "发起卷积失败，物料不存在！");
        }
        addData(materialConvolution, materialInfo);
    }

    /**
     * 新增数据
     *
     * @param materialConvolution 物料成本卷积记录
     * @param materialInfo        物料信息
     */
    @Transactional
    void addData(MaterialConvolution materialConvolution, Map<String, Object> materialInfo) {
        String materialNo = materialConvolution.getMaterialNo();
        String region = materialConvolution.getRegion();
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        int num = materialConvolutionDao.getIllegalConvolution(materialNo, null, null);
        if (num > 0) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "当前物料存在进行中卷积任务或已在其他地点卷积，请与管理员联系！");
        }
        Map<String, Object> validResult = convolutionInterface.checkMaterial(materialNo, String.valueOf(RegionEnum.getValueByName(region)));
        materialConvolution.setMaterialName((String) materialInfo.get("pt_desc1"));
        String id = SnowFlake.nextIdStr();
        materialConvolution.setId(id);
        materialConvolution.setCreateUser(currentUser.getId());
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        materialConvolution.setCreateTime(currentTime);
        MaterialConvolutionLog materialConvolutionLog = new MaterialConvolutionLog();
        materialConvolutionLog.setId(SnowFlake.nextIdStr());
        materialConvolutionLog.setConvolutionId(id);
        materialConvolutionLog.setNode(1);
        materialConvolutionLog.setSerial(1);
        materialConvolutionLog.setStatus(0);
        materialConvolutionLog.setCreateTime(currentTime);
        materialConvolutionLogDao.insert(materialConvolutionLog);
        if (validResult.containsKey("return_result") && StringUtils.equals("True", (String) validResult.get("return_result"))) {
            String rollupId = SnowFlake.nextIdStr();
            Map<String, Object> startResult = convolutionInterface.rollingMaterialPrice(rollupId, materialNo, String.valueOf(RegionEnum.getValueByName(region)));
            materialConvolution.setStatus(ConvolutionStatusTypeEnum.CONVOLUTION_PROGRESSING.getValue());
            materialConvolutionDao.insert(materialConvolution);
            materialConvolutionLog.setStatus(1);
            materialConvolutionLog.setContent((String) validResult.get("return_ref"));
            materialConvolutionLogDao.updateById(materialConvolutionLog);
            MaterialConvolutionLog rollupLog = new MaterialConvolutionLog();
            rollupLog.setId(SnowFlake.nextIdStr());
            rollupLog.setConvolutionId(id);
            rollupLog.setRecordId(rollupId);
            rollupLog.setNode(2);
            rollupLog.setSerial(2);
            rollupLog.setStatus(0);
            rollupLog.setCreateTime(currentTime);
            materialConvolutionLogDao.insert(rollupLog);
            if (startResult.containsKey("return_result") && StringUtils.equals("s_received", (String) startResult.get("return_result"))) {
                MaterialRollup materialRollup = new MaterialRollup();
                materialRollup.setId(rollupId);
                materialRollup.setConvolutionId(id);
                materialRollup.setStatus(0);
                materialRollup.setCreateUser(currentUser.getId());
                materialRollup.setCreateTime(currentTime);
                materialRollupDao.insert(materialRollup);
                rollupLog.setStatus(0);
                materialConvolutionLogDao.updateById(rollupLog);
                push(materialConvolution, currentUser.getId(), currentTime);
            } else {
                rollupLog.setStatus(2);
                materialConvolutionLogDao.updateById(rollupLog);
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR,
                        ObjectUtils.isEmpty(startResult.get("return_ref"))? "卷积服务器未返回信息": (String) startResult.get("return_ref"));
            }
        } else {
            materialConvolution.setStatus(ConvolutionStatusTypeEnum.CHECK_FAILED.getValue());
            materialConvolutionDao.insert(materialConvolution);
            materialConvolutionLog.setStatus(2);
            materialConvolutionLog.setContent((String) validResult.get("return_ref"));
            materialConvolutionLogDao.updateById(materialConvolutionLog);
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, (String) validResult.get("return_ref"));
        }
    }

    /**
     * 物料卷积消息推送
     *
     * @param materialConvolution 物料卷积记录
     * @param operateUser         当前操作人
     * @param currentTime         当前时间
     */
    private void push(MaterialConvolution materialConvolution, String operateUser, String currentTime) {
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        List<Notification> notificationList = new ArrayList<>();
        int status = materialConvolution.getStatus();
        String region = RegionEnum.getValueByName(materialConvolution.getRegion());
        String content = "物料【" + materialConvolution.getMaterialNo() + " | " + materialConvolution.getMaterialName() + "】 在【" + region + "】 地点" + ConvolutionStatusTypeEnum.getNameByValue(status);
        List<String> targetList = new ArrayList<>();
        targetList.add(operateUser);
        if (status == ConvolutionStatusTypeEnum.COST_VERIFIED.getValue()) {
            String targetFinancial = "";
            if (StringUtils.equals(region, RegionConstants.WPCNJ)) {
                targetFinancial = String.valueOf(parameterDao.getParameterByName(SystemConstants.WPCNJ_TARGET_USER).getValue());
            } else if (StringUtils.equals(region, RegionConstants.WSCNJ)) {
                targetFinancial = String.valueOf(parameterDao.getParameterByName(SystemConstants.WSCNJ_TARGET_USER).getValue());
            } else if (StringUtils.equals(region, RegionConstants.SWTNJ)) {
                targetFinancial = String.valueOf(parameterDao.getParameterByName(SystemConstants.SWTNJ_TARGET_USER).getValue());
            }
            if (StringUtils.isNotEmpty(targetFinancial)) {
                targetList.addAll(Arrays.asList(targetFinancial.split(",")));
            }
        }
        if (StringUtils.isNotEmpty(materialConvolution.getCopyUser())) {
            targetList.addAll(Arrays.asList(materialConvolution.getCopyUser().split(",")));
        }
        List<String> targetUserList = targetList.stream().distinct().collect(Collectors.toList());
        for (String tar : targetUserList) {
            if (!userMap.containsKey(tar)) {
                continue;
            }
            Notification notification = new Notification();
            notification.setId(SnowFlake.nextIdStr());
            notification.setCreateTime(currentTime);
            notification.setCreateUser(operateUser);
            notification.setSourceId(materialConvolution.getId());
            notification.setContent(content);
            notification.setDealUser(tar);
            notification.setSourceType(NotificationSourceEnum.CONVOLUTION_MODULE.getValue());
            notificationList.add(notification);
            Map<String, String> contentMap = new HashMap<>();
            contentMap.put("title", "您有一条新消息待查看");
            contentMap.put("description", notification.getContent());
            String contentStr = JSON.toJSONString(contentMap);
            Map<String, String> targetUser = userMap.get(tar);
            messagePushService.pushMessage(contentStr, targetUser.get("sn"));
        }
        notificationDao.insertBatch(notificationList);
        MessageConfiguration messageConfiguration = new MessageConfiguration();
        messageConfiguration.setBusinessType(MessagePushBusinessEnum.CONVOLUTION.getValue());
        messageConfiguration.setContent(content);
        messageConfiguration.setContentType(MessageContentTypeEnum.TEXT_CARD.getValue());
        weChatMessageInterface.pushMessage(targetUserList, null, messageConfiguration, currentTime);
    }

    @Override
    public void deleteMaterialConvolution(String id) {
        MaterialConvolution materialConvolution = materialConvolutionDao.selectById(id);
        if (ObjectUtils.isEmpty(materialConvolution)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除失败，卷积记录不存在！");
        }
        materialConvolution.setStatus(ConvolutionStatusTypeEnum.CONVOLUTION_ABOLISH.getValue());
        materialConvolutionDao.updateById(materialConvolution);
    }

    @Override
    public ImportResp importConvolutions(String fileName) {
        String filePath = fileName;
        return excelImportService.excelFile(filePath, 2, new ExcelImportCallBack() {
            @Override
            public Collection<RowError> checkRow(String[] record) {
                return checkRecordValid(record);
            }

            @Override
            public boolean persistRowToDb(String[] record) {
                MaterialConvolutionImportDto materialConvolution = covertToBean(record);
                return false;
//				try {
//					materialReplaceDao.insert(mocDetail);
//					return true;
//				} catch (Exception e) {
//					return false;
//				}
            }

            @Override
            public ImportResp partFailure(ImportResp resp) {
                resp.setRetMessage("导入物料成本卷积数据部分失败，总数=" + resp.getTotal() + ",失败总数=" + resp.getFailedTotal());
                return resp;
            }

            @Override
            public ImportResp allSuccess(ImportResp resp) {
                resp.setRetMessage("导入物料成本卷积数据全部成功，总数=" + resp.getTotal());
                return resp;
            }

            @Override
            public List<Map> convertFailList(List<String[]> failRecords) {
                List<Map> list = new ArrayList<>();
                int sort = 1;
                for (String[] failRecord : failRecords) {
                    Map item = new HashMap();
                    item.put("sort", sort);
                    item.put("region", failRecord[1].trim().toUpperCase());
                    item.put("material", failRecord[2].trim());
                    list.add(item);
                    sort++;
                }
                return list;
            }

        });
    }

    @Override
    public ImportResp batchAddConvolution(List<MaterialConvolutionImportDto> dataList, Map<String, Object> otherParameter) {
        List<MaterialConvolutionImportDto> oldList = dataList.stream().filter(item -> StringUtils.isNotEmpty(item.getId())).collect(Collectors.toList());
        List<Map> failedList = new ArrayList<>();
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        // 纯新增
        if (ObjectUtils.isEmpty(oldList)) {
//            List<String> convolutionList = dataList.stream().map(MaterialConvolutionImportDto::getMaterial).collect(Collectors.toList());
            int sort = 1;
            for (MaterialConvolutionImportDto dto : dataList) {
                String materialNo = dto.getMaterial();
//                String region = dto.getRegion();
                String region = StringUtils.equals(dto.getRegion(), RegionEnum.WSCNJ.getName()) ?
                        RegionEnum.WPCNJ.getName() : dto.getRegion();
                Map item = ObjectUtils.object2Map(dto);
                item.put("id", SnowFlake.nextIdStr());
                Map<String, Object> materialInfo = syncService.getOneMaterial(materialNo, region);
                if (ObjectUtils.isEmpty(materialInfo)) {
                    item.put("message", "物料不存在！");
                    item.put("sort", sort);
                    failedList.add(item);
                    sort++;
                    continue;
                }
                int num = materialConvolutionDao.getIllegalConvolution(materialNo, null, null);
                if (num > 0) {
                    item.put("message", "当前物料存在进行中卷积任务或已在其他地点卷积，请与管理员联系！");
                    item.put("sort", sort);
                    failedList.add(item);
                    sort++;
                    continue;
                }
                Map<String, Object> validResult = convolutionInterface.checkMaterial(materialNo, String.valueOf(RegionEnum.getValueByName(dto.getRegion())));
                MaterialConvolution materialConvolution = new MaterialConvolution();
                materialConvolution.setMaterialNo(materialNo);
                materialConvolution.setRegion(dto.getRegion());
                materialConvolution.setCopyUser(ObjectUtils.isEmpty(otherParameter) || !otherParameter.containsKey("copyUser") ? "" : (String) otherParameter.get("copyUser"));
                materialConvolution.setRemark(ObjectUtils.isEmpty(otherParameter) || !otherParameter.containsKey("remark") ? "" : (String) otherParameter.get("remark"));
                materialConvolution.setMaterialName((String) materialInfo.get("pt_desc1"));
                String id = SnowFlake.nextIdStr();
                materialConvolution.setId(id);
                materialConvolution.setCreateUser(currentUser.getId());
                String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
                materialConvolution.setCreateTime(currentTime);
                MaterialConvolutionLog materialConvolutionLog = new MaterialConvolutionLog();
                materialConvolutionLog.setId(SnowFlake.nextIdStr());
                materialConvolutionLog.setConvolutionId(id);
                materialConvolutionLog.setNode(1);
                materialConvolutionLog.setSerial(1);
                materialConvolutionLog.setStatus(0);
                materialConvolutionLog.setCreateTime(currentTime);
                materialConvolutionLogDao.insert(materialConvolutionLog);
                if (validResult.containsKey("return_result") && StringUtils.equals("True", (String) validResult.get("return_result"))) {
                    String rollupId = SnowFlake.nextIdStr();
                    Map<String, Object> startResult = convolutionInterface.rollingMaterialPrice(rollupId, materialNo, String.valueOf(RegionEnum.getValueByName(region)));
                    materialConvolution.setStatus(ConvolutionStatusTypeEnum.CONVOLUTION_PROGRESSING.getValue());
                    materialConvolutionDao.insert(materialConvolution);
                    materialConvolutionLog.setStatus(1);
                    materialConvolutionLog.setContent((String) validResult.get("return_ref"));
                    materialConvolutionLogDao.updateById(materialConvolutionLog);
                    MaterialConvolutionLog rollupLog = new MaterialConvolutionLog();
                    rollupLog.setId(SnowFlake.nextIdStr());
                    rollupLog.setConvolutionId(id);
                    rollupLog.setRecordId(rollupId);
                    rollupLog.setNode(2);
                    rollupLog.setSerial(2);
                    rollupLog.setStatus(0);
                    rollupLog.setCreateTime(currentTime);
                    materialConvolutionLogDao.insert(rollupLog);
                    if (startResult.containsKey("return_result") && StringUtils.equals("s_received", (String) startResult.get("return_result"))) {
                        MaterialRollup materialRollup = new MaterialRollup();
                        materialRollup.setId(rollupId);
                        materialRollup.setConvolutionId(id);
                        materialRollup.setStatus(0);
                        materialRollup.setCreateUser(currentUser.getId());
                        materialRollup.setCreateTime(currentTime);
                        materialRollupDao.insert(materialRollup);
                        rollupLog.setStatus(0);
                        materialConvolutionLogDao.updateById(rollupLog);
                        push(materialConvolution, currentUser.getId(), currentTime);
                    } else {
                        rollupLog.setStatus(2);
                        materialConvolutionLogDao.updateById(rollupLog);
                        item.put("message", startResult.get("return_ref"));
                        item.put("sort", sort);
                        failedList.add(item);
                        sort++;
                        continue;
                    }
                } else {
                    materialConvolution.setStatus(ConvolutionStatusTypeEnum.CHECK_FAILED.getValue());
                    materialConvolutionDao.insert(materialConvolution);
                    materialConvolutionLog.setStatus(2);
                    materialConvolutionLog.setContent((String) validResult.get("return_ref"));
                    materialConvolutionLogDao.updateById(materialConvolutionLog);
                    item.put("message", validResult.get("return_ref"));
                    item.put("sort", sort);
                    failedList.add(item);
                    sort++;
                    continue;
                }
            }
        } else {
            // 二次导入
            int sort = 1;
            for (MaterialConvolutionImportDto dto : dataList) {
                String materialNo = dto.getMaterial();
//                String region = dto.getRegion();
                String region = StringUtils.equals(dto.getRegion(), RegionEnum.WSCNJ.getName()) ?
                        RegionEnum.WPCNJ.getName() : dto.getRegion();
                Map item = ObjectUtils.object2Map(dto);
                Map<String, Object> materialInfo = syncService.getOneMaterial(materialNo, region);
                if (ObjectUtils.isEmpty(materialInfo)) {
                    item.put("message", "物料不存在！");
                    item.put("sort", sort);
                    failedList.add(item);
                    sort++;
                    continue;
                }
                int num = materialConvolutionDao.getIllegalConvolution(materialNo, null, null);
                if (num > 0) {
                    item.put("message", "当前物料存在进行中卷积任务或已在其他地点卷积，请与管理员联系！");
                    item.put("sort", sort);
                    failedList.add(item);
                    sort++;
                    continue;
                }
                Map<String, Object> validResult = convolutionInterface.checkMaterial(materialNo, String.valueOf(RegionEnum.getValueByName(dto.getRegion())));
                MaterialConvolution materialConvolution = new MaterialConvolution();
                materialConvolution.setMaterialNo(materialNo);
                materialConvolution.setRegion(dto.getRegion());
                materialConvolution.setCopyUser(ObjectUtils.isEmpty(otherParameter) || !otherParameter.containsKey("copyUser") ? "" : (String) otherParameter.get("copyUser"));
                materialConvolution.setRemark(ObjectUtils.isEmpty(otherParameter) || !otherParameter.containsKey("remark") ? "" : (String) otherParameter.get("remark"));
                materialConvolution.setMaterialName((String) materialInfo.get("pt_desc1"));
                String id = SnowFlake.nextIdStr();
                materialConvolution.setId(id);
                materialConvolution.setCreateUser(currentUser.getId());
                String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
                materialConvolution.setCreateTime(currentTime);
                MaterialConvolutionLog materialConvolutionLog = new MaterialConvolutionLog();
                materialConvolutionLog.setId(SnowFlake.nextIdStr());
                materialConvolutionLog.setConvolutionId(id);
                materialConvolutionLog.setNode(1);
                materialConvolutionLog.setSerial(1);
                materialConvolutionLog.setStatus(0);
                materialConvolutionLog.setCreateTime(currentTime);
                materialConvolutionLogDao.insert(materialConvolutionLog);
                if (validResult.containsKey("return_result") && StringUtils.equals("True", (String) validResult.get("return_result"))) {
                    String rollupId = SnowFlake.nextIdStr();
                    Map<String, Object> startResult = convolutionInterface.rollingMaterialPrice(rollupId, materialNo, String.valueOf(RegionEnum.getValueByName(region)));
                    materialConvolution.setStatus(ConvolutionStatusTypeEnum.CONVOLUTION_PROGRESSING.getValue());
                    materialConvolutionDao.insert(materialConvolution);
                    materialConvolutionLog.setStatus(1);
                    materialConvolutionLog.setContent((String) validResult.get("return_ref"));
                    materialConvolutionLogDao.updateById(materialConvolutionLog);
                    MaterialConvolutionLog rollupLog = new MaterialConvolutionLog();
                    rollupLog.setId(SnowFlake.nextIdStr());
                    rollupLog.setConvolutionId(id);
                    rollupLog.setRecordId(rollupId);
                    rollupLog.setNode(2);
                    rollupLog.setSerial(2);
                    rollupLog.setStatus(0);
                    rollupLog.setCreateTime(currentTime);
                    materialConvolutionLogDao.insert(rollupLog);
                    if (startResult.containsKey("return_result") && StringUtils.equals("s_received", (String) startResult.get("return_result"))) {
                        MaterialRollup materialRollup = new MaterialRollup();
                        materialRollup.setId(rollupId);
                        materialRollup.setConvolutionId(id);
                        materialRollup.setStatus(0);
                        materialRollup.setCreateUser(currentUser.getId());
                        materialRollup.setCreateTime(currentTime);
                        materialRollupDao.insert(materialRollup);
                        rollupLog.setStatus(0);
                        materialConvolutionLogDao.updateById(rollupLog);
                        push(materialConvolution, currentUser.getId(), currentTime);
                    } else {
                        rollupLog.setStatus(2);
                        materialConvolutionLogDao.updateById(rollupLog);
                        item.put("message", startResult.get("return_ref"));
                        item.put("sort", sort);
                        failedList.add(item);
                        sort++;
                    }
                } else {
                    materialConvolution.setStatus(ConvolutionStatusTypeEnum.CHECK_FAILED.getValue());
                    materialConvolutionDao.insert(materialConvolution);
                    materialConvolutionLog.setStatus(2);
                    materialConvolutionLog.setContent((String) validResult.get("return_ref"));
                    materialConvolutionLogDao.updateById(materialConvolutionLog);
                    item.put("message", validResult.get("return_ref"));
                    item.put("sort", sort);
                    failedList.add(item);
                    sort++;
                }
            }
        }
        ImportResp resp = new ImportResp();
        resp.setFailedList(failedList);
        resp.setRetCode((failedList.size() > 0) ? ReturnCodes.HTTP_IMPORT_PART_FAIL
                .getRetCode() : ReturnCodes.HTTP_SUCCESS.getRetCode());
        resp.setRetMessage((failedList.size() > 0) ? "导入成本卷积信息部分成功" : "导入成本卷积信息成功");
        return resp;
    }

    @Override
    public void exportMaterialConvolution(HttpServletResponse response) {

    }

    @Override
    public Map<String, Object> getOneMaterial(String materialNo) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> infoList = syncService.getPgsSiteMaterialInfo(materialNo);
//        List<Map<String, Object>> infoList = syncService.getPgsMaterialInfo(materialNo);
        for (Map<String, Object> dto : infoList) {
            String region = (String) dto.get("pt_domain");
            String site = dto.containsKey("ptp_site") ? (String) dto.get("ptp_site") : "";
            if (StringUtils.equals(region, RegionConstants.WPCNJ)) {
                if (StringUtils.isEmpty(site)) {
                    resultMap.put("wpcStatus", dto.get("pt_status"));
                    resultMap.put("wpcPm", dto.get("pt_pm_code"));
                } else if (StringUtils.equals(site, RegionEnum.WPCNJ.getValue())) {
                    resultMap.put("wpcStatus", dto.get("pt_status"));
                    resultMap.put("wpcPm", dto.get("ptp_pm_code"));
                } else if (StringUtils.equals(site, RegionEnum.WSCNJ.getValue())) {
                    resultMap.put("wscStatus", dto.get("pt_status"));
                    resultMap.put("wscPm", dto.get("ptp_pm_code"));
                }
            } else if (StringUtils.equals(region, RegionConstants.WSCNJ)) {
                resultMap.put("wscStatus", dto.get("pt_status"));
                resultMap.put("wscPm", dto.get("pt_pm_code"));
            } else if (StringUtils.equals(region, RegionConstants.SWTNJ)) {
                resultMap.put("swtStatus", dto.get("pt_status"));
                resultMap.put("swtPm", dto.get("pt_pm_code"));
            }
        }
        return resultMap;
    }

    @Override
    @Transactional
    public void updateMaterialConvolutionStatus(String id, int operate, String targetStatus) {
        MaterialConvolution materialConvolution = materialConvolutionDao.selectById(id);
        if (ObjectUtils.isEmpty(materialConvolution)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "操作失败，物料成本卷积记录不存在！");
        }
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (!StringUtils.equals(currentUser.getId(), materialConvolution.getCreateUser())) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "操作失败，用户无权限操作！");
        }
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        materialConvolution.setUpdateUser(currentUser.getId());
        materialConvolution.setUpdateTime(currentTime);
        int currentSort = materialConvolutionLogDao.getCurrentSort(id);
        MaterialConvolutionLog materialConvolutionLog = new MaterialConvolutionLog();
        String logId = SnowFlake.nextIdStr();
        materialConvolutionLog.setId(logId);
        materialConvolutionLog.setConvolutionId(id);
        materialConvolutionLog.setCreateTime(currentTime);
        materialConvolutionLog.setSerial(currentSort + 1);
        if (operate == 1) {
            // 重新提交
            if (materialConvolution.getStatus() != ConvolutionStatusTypeEnum.CHECK_FAILED.getValue()
                    && materialConvolution.getStatus() != ConvolutionStatusTypeEnum.CONVOLUTION_FINISHED.getValue()) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "操作失败，物料成本卷积记录状态异常！");
            }
            int num = materialConvolutionDao.getIllegalConvolution(materialConvolution.getMaterialNo(), null, null);
            if (num > 1) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "当前物料存在进行中卷积任务或已在其他地点卷积，请与管理员联系！");
            }
            Map<String, Object> validResult = convolutionInterface.checkMaterial(materialConvolution.getMaterialNo(), String.valueOf(RegionEnum.getValueByName(materialConvolution.getRegion())));
            materialConvolutionLog.setStatus(0);
            materialConvolutionLogDao.insert(materialConvolutionLog);
            if (validResult.containsKey("return_result") && StringUtils.equals("True", (String) validResult.get("return_result"))) {
                String rollupId = SnowFlake.nextIdStr();
                Map<String, Object> startResult = convolutionInterface.rollingMaterialPrice(rollupId, materialConvolution.getMaterialNo(), String.valueOf(RegionEnum.getValueByName(materialConvolution.getRegion())));
                materialConvolution.setStatus(ConvolutionStatusTypeEnum.CONVOLUTION_PROGRESSING.getValue());
                materialConvolutionDao.updateById(materialConvolution);
                materialConvolutionLog.setStatus(1);
                materialConvolutionLog.setContent((String) validResult.get("return_ref"));
                materialConvolutionLogDao.updateById(materialConvolutionLog);
                MaterialConvolutionLog rollupLog = new MaterialConvolutionLog();
                rollupLog.setId(SnowFlake.nextIdStr());
                rollupLog.setConvolutionId(id);
                rollupLog.setRecordId(rollupId);
                rollupLog.setNode(2);
                rollupLog.setSerial(2);
                rollupLog.setStatus(0);
                rollupLog.setCreateTime(currentTime);
                materialConvolutionLogDao.insert(rollupLog);
                if (startResult.containsKey("return_result") && StringUtils.equals("s_received", (String) startResult.get("return_result"))) {
                    MaterialRollup materialRollup = new MaterialRollup();
                    materialRollup.setId(rollupId);
                    materialRollup.setConvolutionId(id);
                    materialRollup.setStatus(0);
                    materialRollup.setCreateUser(currentUser.getId());
                    materialRollup.setCreateTime(currentTime);
                    materialRollupDao.insert(materialRollup);
                    rollupLog.setStatus(1);
                    materialConvolutionLogDao.updateById(rollupLog);
                    push(materialConvolution, currentUser.getId(), currentTime);
                } else {
                    rollupLog.setStatus(2);
                    materialConvolutionLogDao.updateById(rollupLog);
                    throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, ObjectUtils.isEmpty(startResult.get("return_ref"))? "卷积服务器未返回信息": (String) startResult.get("return_ref"));
                }
            } else {
                materialConvolution.setStatus(ConvolutionStatusTypeEnum.CHECK_FAILED.getValue());
                materialConvolutionDao.updateById(materialConvolution);
                materialConvolutionLog.setStatus(2);
                materialConvolutionLog.setContent((String) validResult.get("return_ref"));
                materialConvolutionLogDao.updateById(materialConvolutionLog);
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, (String) validResult.get("return_ref"));
            }
//                String rollupId = SnowFlake.nextIdStr();
//                Map<String, Object> startResult = convolutionInterface.rollingMaterialPrice(rollupId, materialConvolution.getMaterialNo(), String.valueOf(RegionEnum.getValueByName(materialConvolution.getRegion())));
//                if (startResult.containsKey("return_result") && StringUtils.equals("s_received", (String) startResult.get("return_result"))) {
//                    MaterialRollup materialRollup = new MaterialRollup();
//                    materialRollup.setId(rollupId);
//                    materialRollup.setConvolutionId(id);
//                    materialRollup.setStatus(0);
//                    materialRollup.setCreateUser(currentUser.getId());
//                    materialRollup.setCreateTime(currentTime);
//                    materialRollupDao.insert(materialRollup);
//                    materialConvolutionLog.setRecordId(rollupId);
//                    materialConvolutionLog.setNode(2);
//                    materialConvolutionLog.setStatus(0);
//                    materialConvolutionLogDao.insert(materialConvolutionLog);
//                    materialConvolution.setStatus(ConvolutionStatusTypeEnum.CONVOLUTION_PROGRESSING.getValue());
//                    materialConvolutionDao.updateById(materialConvolution);
//                    return;
//                } else {
//                    throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, (String) startResult.get("return_ref"));
//                }
//            } else {
//
//            }
            return;
        }
        if (operate == 2) {
            // 成本确认
            if (materialConvolution.getStatus() != ConvolutionStatusTypeEnum.CONVOLUTION_FINISHED.getValue()) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "操作失败，物料成本卷积记录状态异常！");
            }
//            materialConvolutionLog.setRecordId(rollupId);
            materialConvolutionLog.setNode(3);
            materialConvolutionLog.setStatus(1);
            materialConvolutionLogDao.insert(materialConvolutionLog);
            materialConvolution.setStatus(ConvolutionStatusTypeEnum.COST_VERIFIED.getValue());
            materialConvolutionDao.updateById(materialConvolution);
            push(materialConvolution, currentUser.getId(), currentTime);
            return;
        }
        if (operate == 3) {
            // 同步成本
            if (materialConvolution.getStatus() != ConvolutionStatusTypeEnum.COST_VERIFIED.getValue()) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "操作失败，物料成本卷积记录状态异常！");
            }
//            materialConvolutionLog.setRecordId(rollupId);
            materialConvolutionLog.setNode(3);
            materialConvolutionLog.setStatus(0);
            materialConvolutionLogDao.insert(materialConvolutionLog);
            System.out.println("成本同步中");
            log.info("成本同步中");
            // todo 成本同步
            return;
        }
        if (operate == 4) {
            // 修改状态
            if (materialConvolution.getStatus() != ConvolutionStatusTypeEnum.COST_VERIFIED.getValue() &&
                    materialConvolution.getStatus() != ConvolutionStatusTypeEnum.STATUS_FAILED.getValue() &&
                    materialConvolution.getStatus() != ConvolutionStatusTypeEnum.STATUS_FINISHED.getValue()) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "操作失败，物料成本卷积记录状态异常！");
            }
            Map<String, Object> statusResult = convolutionInterface.getMaterialStatus(materialConvolution.getMaterialNo(), RegionEnum.getValueByName(materialConvolution.getRegion()));
            if (statusResult.containsKey("return_result") && StringUtils.equals((String) statusResult.get("return_result"), "A")) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "操作失败，物料状态为A，不可再次修改状态！");
            }
            Map<String, Object> changeResult = convolutionInterface.changeMaterialStatus(logId, materialConvolution.getMaterialNo(), RegionEnum.getValueByName(materialConvolution.getRegion()), targetStatus);
            if (changeResult.containsKey("return_result") && StringUtils.equals("s_received", (String) changeResult.get("return_result"))) {
                materialConvolutionLog.setNode(5);
                materialConvolutionLog.setStatus(0);
                materialConvolutionLog.setTargetContent(targetStatus);
                materialConvolutionLogDao.insert(materialConvolutionLog);
                materialConvolution.setStatus(ConvolutionStatusTypeEnum.STATUS_CHANGING.getValue());
                materialConvolutionDao.updateById(materialConvolution);
                push(materialConvolution, currentUser.getId(), currentTime);
                return;
            } else {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, (String) changeResult.get("return_ref"));
            }
        }
        throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "操作不合法！");
    }

    @Override
    public Map<String, Object> queryConvolutionConfig() {
        Map<String, Object> map = new HashMap<>();
        SystemParameter sp_wpc = parameterDao.getParameterByName(SystemConstants.WPCNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_wpc)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "wpc未配置");
        }
        map.put("wpcUser", sp_wpc.getValue());
        SystemParameter sp_wsc = parameterDao.getParameterByName(SystemConstants.WSCNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_wsc)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "wsc未配置");
        }
        map.put("wscUser", sp_wsc.getValue());
        SystemParameter sp_swt = parameterDao.getParameterByName(SystemConstants.SWTNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_swt)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "swt未配置");
        }
        map.put("swtUser", sp_swt.getValue());
        return map;
    }

    @Override
    @Transactional
    public void updateConvolutionConfig(String wpcUser, String wscUser, String swtUser) {
        SystemParameter sp_wpc = parameterDao.getParameterByName(SystemConstants.WPCNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_wpc)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        sp_wpc.setValue(wpcUser);
        parameterDao.updateById(sp_wpc);
        SystemParameter sp_wsc = parameterDao.getParameterByName(SystemConstants.WSCNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_wsc)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        sp_wsc.setValue(wscUser);
        parameterDao.updateById(sp_wsc);
        SystemParameter sp_swt = parameterDao.getParameterByName(SystemConstants.SWTNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_swt)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        sp_swt.setValue(swtUser);
        parameterDao.updateById(sp_swt);
    }

    @Override
    public Map<String, Object> getConvolutionInfo(String id) {
        MaterialConvolution materialConvolution = materialConvolutionDao.selectById(id);
        if (ObjectUtils.isEmpty(materialConvolution)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "物料成本卷积记录不存在！");
        }
        Map<String, Object> map = ObjectUtils.object2Map(materialConvolution);
        map.put("operateUserName", userDao.selectById(materialConvolution.getCreateUser()).getName());
        map.put("statusName", ConvolutionStatusTypeEnum.getNameByValue(materialConvolution.getStatus()));
        if (StringUtils.isNotEmpty(materialConvolution.getCopyUser())) {
            Map<String, Map<String, String>> userMap = userDao.getUserMap();
            List<String> copyList = Arrays.asList(materialConvolution.getCopyUser().split(","));
            List<String> userNameList = new ArrayList<>(copyList.size());
            for (String copyUser : copyList) {
                if (userMap.containsKey(copyUser)) {
                    userNameList.add(userMap.get(copyUser).get("name"));
                }
            }
            map.put("copyUserName", ObjectUtils.isEmpty(userNameList) ? "" : StringUtils.strip(userNameList.toString(), "[]"));
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> getErrorList(String id, String processId) {
        List<Map<String, Object>> errorList = new ArrayList<>();
        if (StringUtils.isEmpty(processId)) {
            MaterialRollup materialRollup = materialRollupDao.getLatestRecord(id);
            if (ObjectUtils.isEmpty(materialRollup)) {
                return errorList;
            }
            Map<String, Object> queryParam = new HashMap<>();
            queryParam.put("rollupId", materialRollup.getId());
            queryParam.put("startNum", 0);
            queryParam.put("pageSize", 10);
            List<MaterialRollupResult> materialRollupResultList = materialRollupResultDao.pageRollupResultList(queryParam);
            int sort = 1;
            for (MaterialRollupResult result : materialRollupResultList) {
                Map<String, Object> item = ObjectUtils.object2Map(result);
                item.put("sort", sort);
                errorList.add(item);
                sort++;
            }
            return errorList;
        } else {
            MaterialConvolutionLog logInfo = materialConvolutionLogDao.selectById(processId);
            if (logInfo.getNode() == 2) {
//                MaterialRollup materialRollup = materialRollupDao.selectById(logInfo.getRecordId());
                Map<String, Object> queryParam = new HashMap<>();
                queryParam.put("rollupId", logInfo.getRecordId());
                queryParam.put("startNum", 0);
                queryParam.put("pageSize", 10);
                List<MaterialRollupResult> materialRollupResultList = materialRollupResultDao.pageRollupResultList(queryParam);
                int sort = 1;
                for (MaterialRollupResult result : materialRollupResultList) {
                    Map<String, Object> item = ObjectUtils.object2Map(result);
                    item.put("sort", sort);
                    errorList.add(item);
                    sort++;
                }
                return errorList;
            }
            if (logInfo.getStatus() != 2) {
                return errorList;
            }
            Map<String, Object> logError = (Map<String, Object>) JSON.parse(logInfo.getContent());
            List<Map<String, Object>> logErrorList = (List<Map<String, Object>>) logError.get("rtnbody");
            int sort = 1;
            for (Map<String, Object> object : logErrorList) {
                Map<String, Object> item = object;
                item.put("sort", sort);
                errorList.add(item);
                sort++;
            }
            return errorList;
        }
    }

    @Override
    public List<Map<String, Object>> getConvolutionProcessInfo(String id) {
        MaterialConvolution materialConvolution = materialConvolutionDao.selectById(id);
        if (ObjectUtils.isEmpty(materialConvolution)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "物料成本卷积记录不存在！");
        }
        List<MaterialConvolutionLog> logList = materialConvolutionLogDao.getProcessList(id);
        List<Map<String, Object>> processList = new ArrayList<>();
//        Map<String,Object> startNode = new HashMap<>();
//        startNode.put("createTime",materialConvolution.getCreateTime());
//        startNode.put("node",1);
//        processList.add(startNode);
        for (MaterialConvolutionLog logInfo : logList) {
            Map<String, Object> item = ObjectUtils.object2Map(logInfo);
            processList.add(item);
        }
        return processList;
    }

    @Override
    @Transactional
    public void updateStatusOut(String id, String content) {
        MaterialConvolutionLog logInfo = materialConvolutionLogDao.selectById(id);
        if (ObjectUtils.isEmpty(logInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "记录不存在！");
        }
        if (logInfo.getStatus() != 0) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "已处理过当前记录，请检查！");
        }
        MaterialConvolution materialConvolution = materialConvolutionDao.selectById(logInfo.getConvolutionId());
        if (ObjectUtils.isEmpty(materialConvolution)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "卷积记录不存在！");
        }
        Map<String, Object> contentMap = (Map<String, Object>) JSON.parse(content);
        boolean success = (boolean) contentMap.get("pmip_result");
//        List<Map<String, Object>> dataList = (List<Map<String, Object>>) contentMap.get("rtnbody");
        String time = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        logInfo.setCreateTime(time);
        logInfo.setStatus(success ? 1 : 2);
        logInfo.setContent(content);
        materialConvolutionLogDao.updateById(logInfo);
        materialConvolution.setStatus(success ? ConvolutionStatusTypeEnum.STATUS_FINISHED.getValue() : ConvolutionStatusTypeEnum.STATUS_FAILED.getValue());
        materialConvolutionDao.updateById(materialConvolution);
        push(materialConvolution, materialConvolution.getCreateUser(), time);
    }

    @Override
    public List<Map<String, Object>> getConvolutionStepInfo(Map<String, Object> queryParam) {
        List<MaterialConvolutionLog> logList = materialConvolutionLogDao.pageConvolutionLogList(queryParam);
        List<Map<String, Object>> dataList = new ArrayList<>(logList.size());
        int sort = (int) queryParam.get("startNum") + 1;
        for (MaterialConvolutionLog info : logList) {
            Map<String, Object> item = ObjectUtils.object2Map(info);
            item.put("sort", sort);
            dataList.add(item);
            sort++;
        }
        return dataList;
    }

    private List<Map<String, Object>> completeResult(List<MaterialConvolution> originalList, int startNum) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        List<UserRoleRelation> roleRelationList = userRoleRelationDao.queryRelationByUserId(currentUser.getId());
        boolean superPermission = false;
        if (!ObjectUtils.isEmpty(roleRelationList)) {
            for (UserRoleRelation userRoleRelation : roleRelationList) {
                if (StringUtils.equals(userRoleRelation.getRoleId(), "1")) {
                    superPermission = true;
                }
            }
        }
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        List<Map<String, Object>> resultList = new ArrayList<>(originalList.size());
        Map<String, Object> managePermissionMap = validManagePermission(currentUser.getId());
        int sort = startNum + 1;
        for (MaterialConvolution record : originalList) {
            Map<String, Object> map = ObjectUtils.object2Map(record);
            map.put("sort", sort);
            map.put("operateUserName", userMap.containsKey(record.getCreateUser()) ? userMap.get(record.getCreateUser()).get("name") : "");
            map.put("statusName", ConvolutionStatusTypeEnum.getNameByValue(record.getStatus()));
            boolean checkPermission = StringUtils.equals(currentUser.getId(), record.getCreateUser());
            boolean managePermission = managePermissionMap.containsKey(record.getRegion());
            if (StringUtils.isNotEmpty(record.getCopyUser())) {
                List<String> copyList = Arrays.asList(record.getCopyUser().split(","));
                List<String> userNameList = new ArrayList<>(copyList.size());
                for (String copyUser : copyList) {
                    if (userMap.containsKey(copyUser)) {
                        userNameList.add(userMap.get(copyUser).get("name"));
                    }
                    if (StringUtils.equals(currentUser.getId(), copyUser)) {
                        checkPermission = true;
                    }
                }
                map.put("copyUserName", ObjectUtils.isEmpty(userNameList) ? "" : StringUtils.strip(userNameList.toString(), "[]"));
            }
            if (record.getStatus() == ConvolutionStatusTypeEnum.CONVOLUTION_PROGRESSING.getValue() || record.getStatus() == ConvolutionStatusTypeEnum.STATUS_CHANGING.getValue()) {
                record.getCreateTime();
                int targetRate = 60;
                map.put("targetRate", targetRate);
            }
            map.put("checkPermission", checkPermission || managePermission || superPermission);
            map.put("modifyPermission", StringUtils.equals(currentUser.getId(), record.getCreateUser()) || managePermission || superPermission);
            map.put("managePermission", managePermission || superPermission);
            resultList.add(map);
            sort++;
        }
        return resultList;
    }

    private MaterialConvolutionImportDto covertToBean(String[] record) {
        MaterialConvolutionImportDto materialConvolutionImportDto = new MaterialConvolutionImportDto();
        materialConvolutionImportDto.setMaterial(record[2].trim());
        return materialConvolutionImportDto;
    }

    private Collection<RowError> checkRecordValid(String[] record) {
        List<RowError> rowErrors = new ArrayList<>();
        if (StringUtils.isEmpty(record[1].trim())) {
            addRowError("卷积域不能为空", rowErrors);
        } else if (record[1].trim().length() > 5) {
            addRowError("卷积域长度不能超过5", rowErrors);
        }
        if (StringUtils.isEmpty(record[2].trim())) {
            addRowError("物料号不能为空", rowErrors);
        } else if (record[2].trim().length() > 20) {
            addRowError("物料号长度不能超过20", rowErrors);
        }
        return rowErrors;
    }

    private void addRowError(String errorMessage, List<RowError> rowErrors) {
        RowError rowError = new RowError(errorMessage);
        rowErrors.add(rowError);
    }

    /**
     * 验证是否具备管理权限
     *
     * @param userId 用户id
     * @return 是否具备管理权限
     */
    private Map<String, Object> validManagePermission(String userId) {
        Map<String, Object> resultMap = new HashMap<>();
        SystemParameter sp_wpc = parameterDao.getParameterByName(SystemConstants.WPCNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_wpc)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        List<String> wpcList = Arrays.asList(sp_wpc.getValue().split(","));
        for (String item : wpcList) {
            if (StringUtils.equals(userId, item)) {
                resultMap.put(RegionConstants.WPCNJ, item);
            }
        }
        SystemParameter sp_wsc = parameterDao.getParameterByName(SystemConstants.WSCNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_wsc)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        List<String> wscList = Arrays.asList(sp_wsc.getValue().split(","));
        for (String item : wscList) {
            if (StringUtils.equals(userId, item)) {
                resultMap.put(RegionConstants.WSCNJ, item);
            }
        }
        SystemParameter sp_swt = parameterDao.getParameterByName(SystemConstants.SWTNJ_TARGET_USER);
        if (ObjectUtils.isEmpty(sp_swt)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        List<String> swtList = Arrays.asList(sp_swt.getValue().split(","));
        for (String item : swtList) {
            if (StringUtils.equals(userId, item)) {
                resultMap.put(RegionConstants.SWTNJ, item);
            }
        }
        return resultMap;
    }
}
